<template>
  <div class="cargo-list">
    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <span>货物管理</span>
          <el-button type="primary" @click="handleAdd">新增货物</el-button>
        </div>
      </template>
      
      <el-table
        :data="cargos"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column label="序号" width="80">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="提单号" prop="billNo" />
        <el-table-column label="货物类型" prop="cargoType" />
        <el-table-column label="集装箱尺寸" prop="containerSize" />
        <el-table-column label="重量(吨)" prop="weight" />
        <el-table-column label="货主ID" prop="ownerId" />
        <el-table-column label="存储区域" prop="entryAreaId" />
        <el-table-column label="备注">
          <template #default="scope">
            <el-tooltip 
              :content="scope.row.specialNotes || '无特殊要求'" 
              placement="top"
              :disabled="!scope.row.specialNotes"
            >
              <span>{{ (scope.row.specialNotes || '无').substring(0, 10) }}{{ scope.row.specialNotes && scope.row.specialNotes.length > 10 ? '...' : '' }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button type="primary" link @click="handleView(scope.row)">查看</el-button>
            <el-button type="success" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="warning" link @click="handleExit(scope.row)">出库</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 添加/编辑货物对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form :model="cargoForm" label-width="100px" :rules="formRules" ref="cargoFormRef">
        <el-form-item label="提单号" prop="billNo">
          <el-input v-model="cargoForm.billNo" placeholder="请输入提单号"></el-input>
        </el-form-item>
        <el-form-item label="货物类型" prop="cargoType">
          <el-select v-model="cargoForm.cargoType" placeholder="请选择货物类型">
            <el-option label="集装箱" value="集装箱"></el-option>
            <el-option label="散货" value="散货"></el-option>
            <el-option label="液体" value="液体"></el-option>
            <el-option label="件杂货" value="件杂货"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="集装箱尺寸" prop="containerSize" v-if="cargoForm.cargoType === '集装箱'">
          <el-select v-model="cargoForm.containerSize" placeholder="请选择集装箱尺寸">
            <el-option label="20英尺" value="20英尺"></el-option>
            <el-option label="40英尺" value="40英尺"></el-option>
            <el-option label="45英尺" value="45英尺"></el-option>
            <el-option label="N/A" value="N/A"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="重量(吨)" prop="weight">
          <el-input-number v-model="cargoForm.weight" :min="0" :precision="2" :step="0.1"></el-input-number>
        </el-form-item>
        <el-form-item label="货主ID" prop="ownerId">
          <el-select v-model="cargoForm.ownerId" placeholder="请选择货主">
            <el-option 
              v-for="client in clients" 
              :key="client.clientId" 
              :label="`${client.clientCode} - ${client.companyName}`" 
              :value="client.clientId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="存储区域" prop="entryAreaId">
          <el-select v-model="cargoForm.entryAreaId" placeholder="请选择存储区域">
            <el-option 
              v-for="area in portAreas" 
              :key="area.areaId" 
              :label="`${area.areaCode} - ${area.areaName}`" 
              :value="area.areaId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="特殊要求" prop="specialNotes">
          <el-input 
            v-model="cargoForm.specialNotes" 
            type="textarea" 
            placeholder="请输入特殊要求或备注"
            :rows="3">
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 出库对话框 -->
    <el-dialog
      title="货物出库"
      v-model="exitDialogVisible"
      width="500px"
    >
      <el-form :model="exitForm" label-width="120px" :rules="exitFormRules" ref="exitFormRef">
        <el-form-item label="出库时间" prop="actualExitTime">
          <el-date-picker
            v-model="exitForm.actualExitTime"
            type="datetime"
            placeholder="选择出库时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="操作员" prop="operatorName">
          <el-input v-model="exitForm.operatorName" placeholder="请输入操作员姓名"></el-input>
        </el-form-item>
        <el-form-item label="出库备注" prop="exitNotes">
          <el-input 
            v-model="exitForm.exitNotes" 
            type="textarea" 
            :rows="3"
            placeholder="请输入出库备注信息">
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="exitDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitExitForm">确认出库</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'CargoList',
  setup() {
    const store = useStore()
    const router = useRouter()
    const cargos = ref([])
    const clients = ref([])
    const portAreas = ref([])
    const loading = ref(false)
    const dialogVisible = ref(false)
    const dialogTitle = ref('新增货物')
    const cargoFormRef = ref(null)
    
    // 添加出库对话框相关数据
    const exitDialogVisible = ref(false)
    const exitFormRef = ref(null)
    const currentCargo = ref(null)
    
    // 货物表单数据
    const cargoForm = reactive({
      cargoId: null,
      billNo: '',
      cargoType: '集装箱',
      containerSize: '20英尺',
      weight: 0,
      ownerId: null,
      entryAreaId: null,
      specialNotes: ''
    })
    
    // 表单验证规则
    const formRules = {
      billNo: [
        { required: true, message: '请输入提单号', trigger: 'blur' },
        { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
      ],
      cargoType: [
        { required: true, message: '请选择货物类型', trigger: 'change' }
      ],
      weight: [
        { required: true, message: '请输入重量', trigger: 'blur' }
      ],
      ownerId: [
        { required: true, message: '请选择货主', trigger: 'change' }
      ],
      entryAreaId: [
        { required: true, message: '请选择存储区域', trigger: 'change' }
      ]
    }
    
    // 出库表单数据
    const exitForm = reactive({
      cargoId: null,
      actualExitTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
      operatorName: '',
      exitNotes: ''
    })
    
    // 出库表单验证规则
    const exitFormRules = {
      actualExitTime: [
        { required: true, message: '请选择出库时间', trigger: 'change' }
      ],
      operatorName: [
        { required: true, message: '请输入操作员姓名', trigger: 'blur' }
      ]
    }
    
    // 获取货物列表数据
    const fetchCargos = async () => {
      loading.value = true
      try {
        await store.dispatch('fetchCargos')
        cargos.value = store.getters.cargos
        console.log('获取到的货物数据:', cargos.value)
      } catch (error) {
        console.error('获取货物列表失败:', error)
        ElMessage.error('获取货物列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 获取客户列表
    const fetchClients = async () => {
      try {
        await store.dispatch('fetchClients')
        clients.value = store.getters.clients
      } catch (error) {
        console.error('获取客户列表失败:', error)
      }
    }
    
    // 获取港口区域列表
    const fetchPortAreas = async () => {
      try {
        await store.dispatch('fetchPortAreas')
        portAreas.value = store.getters.portAreas
      } catch (error) {
        console.error('获取港口区域失败:', error)
      }
    }
    
    // 重置表单
    const resetForm = () => {
      cargoForm.cargoId = null
      cargoForm.billNo = ''
      cargoForm.cargoType = '集装箱'
      cargoForm.containerSize = '20英尺'
      cargoForm.weight = 0
      cargoForm.ownerId = null
      cargoForm.entryAreaId = null
      cargoForm.specialNotes = ''
      if (cargoFormRef.value) {
        cargoFormRef.value.resetFields()
      }
    }
    
    // 新增货物
    const handleAdd = () => {
      dialogTitle.value = '新增货物'
      resetForm()
      dialogVisible.value = true
    }
    
    // 查看货物详情
    const handleView = (cargo) => {
      router.push(`/cargos/${cargo.cargoId}`)
    }
    
    // 编辑货物
    const handleEdit = (cargo) => {
      dialogTitle.value = '编辑货物'
      Object.assign(cargoForm, cargo)
      dialogVisible.value = true
    }
    
    // 删除货物
    const handleDelete = (cargo) => {
      ElMessageBox.confirm(
        `确认删除货物"${cargo.billNo}"吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          const response = await axios.delete(`/cargos/${cargo.cargoId}`)
          if (response.data.code === 200) {
            ElMessage.success('删除成功')
            fetchCargos()
          } else {
            ElMessage.error(response.data.message || '删除失败')
          }
        } catch (error) {
          console.error('删除货物失败:', error)
          ElMessage.error('删除货物失败')
        }
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    }
    
    // 添加处理出库方法
    const handleExit = (cargo) => {
      currentCargo.value = cargo
      exitForm.cargoId = cargo.cargoId
      exitDialogVisible.value = true
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!cargoFormRef.value) return
      
      try {
        await cargoFormRef.value.validate()
        
        if (cargoForm.cargoId) {
          // 编辑现有货物
          const response = await axios.put(`/cargos/${cargoForm.cargoId}`, cargoForm)
          if (response.data.code === 200) {
            ElMessage.success('更新货物成功')
            dialogVisible.value = false
            fetchCargos()
          } else {
            ElMessage.error(response.data.message || '更新货物失败')
          }
        } else {
          // 新增货物
          const response = await axios.post('/cargos', cargoForm)
          if (response.data.code === 200) {
            ElMessage.success('添加货物成功')
            dialogVisible.value = false
            fetchCargos()
          } else {
            ElMessage.error(response.data.message || '添加货物失败')
          }
        }
      } catch (error) {
        console.error('表单验证失败:', error)
        ElMessage.error('请检查表单填写是否正确')
      }
    }
    
    // 提交出库表单
    const submitExitForm = async () => {
      if (!exitFormRef.value) return
      
      try {
        await exitFormRef.value.validate()
        
        const response = await axios.put(`cargos/${exitForm.cargoId}/exit`, {
          actualExitTime: exitForm.actualExitTime,
          operatorName: exitForm.operatorName,
          exitNotes: exitForm.exitNotes
        })
        
        if (response.data.code === 200) {
          ElMessage.success('货物出库成功')
          exitDialogVisible.value = false
          fetchCargos()  // 重新获取货物列表，已出库的货物将不再显示
        } else {
          ElMessage.error(response.data.message || '货物出库失败')
        }
      } catch (error) {
        console.error('出库表单验证失败:', error)
        ElMessage.error('请检查出库表单填写是否正确')
      }
    }
    
    onMounted(() => {
      fetchCargos()
      fetchClients()
      fetchPortAreas()
    })
    
    return {
      cargos,
      clients,
      portAreas,
      loading,
      dialogVisible,
      exitDialogVisible,  // 添加出库对话框可见性
      dialogTitle,
      cargoForm,
      exitForm,  // 添加出库表单
      cargoFormRef,
      exitFormRef,  // 添加出库表单引用
      formRules,
      exitFormRules,  // 添加出库表单规则
      currentCargo,  // 添加当前操作的货物
      handleAdd,
      handleView,
      handleEdit,
      handleExit,  // 添加处理出库方法
      handleDelete,
      submitForm,
      submitExitForm  // 添加提交出库表单方法
    }
  }
}
</script>

<style scoped>
.cargo-list {
  padding: 20px;
}

.list-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>